import React, { Component } from 'react';
import styles from './index.module.scss';

import { conversationList,conversation } from '@/api/ai';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import { withConsumer } from '../context';


@withConsumer
@connect(({ ppt }) => ({
  chatsList:ppt.chatsList,
}))
class Comp extends Component {
  componentDidMount = async () => {
    this.props.init(this);
    const {
      value: { changeState,event },
    } = this.props;
    this.throttledGetList((data) => {
      var selectedChat = '';
      if (typeof window !== 'undefined') {
        selectedChat = window.localStorage.getItem('selectedPlanChat');
      }

      var selectedItem = null;
      data.forEach((item) => {
        if (String(item.id) == selectedChat) {
          selectedItem = item;
        }
      });

      var obj = {
        selectedChat: selectedChat ? selectedChat: null,
        selectedItem: selectedItem,
        selectedChatInit:true,
      };

      if (selectedItem) {
        this.getChatDetail(selectedChat);
      }else{
        setTimeout(()=>{
          event.emit('newChat');
        },50)
      }

      changeState(obj);
    });
  };

  throttledGetList = (callback = () => {}) => {
    this.getList(callback);
  };

  // 回话列表
  getList = async (back = () => {}) => {
    const {
      value: { changeState },
    } = this.props;
    var rs = await conversationList();
    if (rs.data?.code == 200) {
      var data = rs.data.data.map((item) => {
        return {
          ...item,
          title: item.theme,
          date: item.created,
        };
      });
      changeState({ chatsList: data });
      setTimeout(() => {
        back(data);
      }, 10);
    }
  };

  // 回话详情 
  getChatDetail = async (chatId) => {
    const {
      value: { event,changeState },
    } = this.props;
    var rs = await conversation({ conversation_id: chatId });
    if (rs.data?.code == 200) {
      var data = rs.data.data;
      if(!data) return 
      var list = data.dialog_segment_list.map((item,i)=>{

        var obj = {
          ...item,
          object:item.artifacts || null,
          role:item.role,
          content:[],
        }

        if(item.content){
          obj.text = item.content
          obj.content = [
            {
              type:'text',
              text:item.content,
              itemData:item,
            }
          ]
        }

        return obj
      })
      console.log(list)
      event.emit('onChatClick', list);
    }
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  render() {
    return (
      <div></div>
    );
  }
}

export default Comp;
